<template>
  <div class="content-block">
      <div class="content-main">
        <div class="content-title">
          <div class="title-text-dot">消息管理</div>
          <div class="title-handle">
            <div class="handel-item">
              <el-button type="primary" size="mini" @click="handleSearch">查 询</el-button>
            </div>
            <div class="handel-item">
              <el-select v-model="readFlag" placeholder="阅读状态" filterable clearable size="mini">
                <el-option
                  v-for="item in readStatusList"
                  :key="item.val"
                  :label="item.name"
                  :value="item.val"
                ></el-option>
              </el-select>
            </div>
            <div class="handel-item">
              <el-select v-model="msgType" placeholder="消息类型" filterable clearable size="mini">
                <el-option
                  v-for="item in msgTypeList"
                  :key="item.val"
                  :label="item.name"
                  :value="item.val"
                ></el-option>
              </el-select>
            </div>
            <div class="handel-item">
              <el-input v-model="title" size="mini" type="text" placeholder="标题"></el-input>
            </div>
            <div class="handel-item">
              <el-button
                type="danger"
                v-if="multipleSelection.length > 0"
                size="mini"
                @click="handleDelete()"
              >
                <i class="fa fa-remove">批量删除</i>
              </el-button>
            </div>
          </div>
        </div>
        <el-table
          :data="messageList"
          ref="mseeageItemTable"
          border
          size="mini"
          height="calc(100vh - 230px)"
          v-loading="tableLoading"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" prop="seq" align="center" :index="indexMethod"></el-table-column>
          <el-table-column label="消息标题" prop="title"></el-table-column>
          <el-table-column width="100" label="消息内容" align="msgContext">
            <template slot-scope="scope">
              <el-button
                size="medium"
                type="text"
                icon="el-icon-news"
                @click="readMsg(scope.row)"
              >查看</el-button>
            </template>
          </el-table-column>
          <el-table-column width="100" label="查看合同" align="msgContext">
            <template slot-scope="scope">
              <el-button
                size="medium"
                type="text"
                icon="el-icon-news"
                @click="toContract(scope.row)"
              >详情</el-button>
            </template>
          </el-table-column>
          <el-table-column label="发送人" prop="sendUser"></el-table-column>
          <el-table-column width="140" align="readDate" label="读取时间">
            <template
              slot-scope="scope"
              v-if="scope.row.readDate"
            >{{ formatTime('yyyy-MM-dd', scope.row.readDate) }}</template>
          </el-table-column>
          <el-table-column width="100" label="消息类型" prop="msgType">
            <template slot-scope="scope">{{ scope.row.msgType | msgFilter }}</template>
          </el-table-column>
          <el-table-column width="100" label="是否已读" prop="readFlag">
            <template slot-scope="scope">{{ scope.row.readFlag === 'Y' ? '已读' : '未读' }}</template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                title="删除"
                class="text-red"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除消息"
      :close-on-click-modal="false"
      :visible.sync="delVisible"
      width="260px"
      center
    >
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="delVisible = false">取 消</el-button>
        <el-button size="mini" type="danger" @click="deleteRow">确 定</el-button>
      </span>
    </el-dialog>
    <!--详情-->
    <el-dialog
      title="消息内容"
      :close-on-click-modal="false"
      :visible.sync="readVisible"
      width="600px"
      center
    >
      <el-row :gutter="20">
        <template v-if="readFrom.msgContext.length === 1">
          <el-col style="padding: 10px" :span="24">
            <div class="result" v-html="readFrom.msgContext[0]"></div>
          </el-col>
        </template>
        <template v-else v-for="(item,index) of readFrom.msgContext">
          <el-col style="padding: 10px" :span="item.indexOf('该阶段已完成')>=0?24:12" :key="index">
            <div :class="{'result':item.indexOf('该阶段')>=0}" v-html="item"></div>
          </el-col>
        </template>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="hasStage" size="mini" @click="readVisible = false;handleStage()">去汇报</el-button>
        <el-button type="primary" size="mini" @click="readVisible = false;getData();">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from "vuex";

export default {
  data() {
    return {
      current: 1,
      pageSize: 10,
      title: "",
      readFlag: "",
      msgType: "",
      total: 10,
      msgId: "",
      tableLoading: false,
      handleVisible: false,
      delVisible: false,
      hasStage: false,
      targetId: "",
      readStatusList: [
        { name: "已阅读", val: "Y" },
        { name: "未阅读", val: "N" }
      ],
      msgTypeList: [
        { name: "审批消息", val: "approve" },
        { name: "预警消息", val: "warning" }
      ],
      readFrom: {
        title: "",
        msgContext: ""
      },
      readVisible: false,
      Ids: [],
      // 所有选中的数据包含跨页数据
      multipleSelectionAll: [],
      // 当前页选中的数据
      multipleSelection: [],
      // 标识列表数据中每一行的唯一键的名称(需要按自己的数据改一下)
      idKey: "msgId"
    };
  },
  computed: {
    ...mapState({
      messageList: state => state.message.messageList
    })
  },
  mounted() {
    let param = this.$route.query;
    if (param) {
      this.title = param.title ? param.title : "";
      this.msgType = param.msgType ? param.msgType : "";
    }
    this.getData();
  },
  methods: {
    ...mapActions("message", [
      "getMessageList",
      "delMessage",
      "delArrMessage",
      "readMessage"
    ]),
    indexMethod(index) {
      return (this.current - 1) * this.pageSize + 1 + index;
    },
    getData() {
      this.tableLoading = true;
      this.getMessageList(this);
    },
    handleSearch() {
      this.current = 1;
      this.getData();
    },
    handleDelete(row) {
      const vm = this;
      if (row) {
        this.msgId = row.msgId;
        vm.Ids = [];
      } else {
        vm.Ids = [];
        vm.multipleSelectionAll.forEach(row => {
          vm.Ids.push(row[vm.idKey]);
        });
        if (vm.Ids.length === 0) {
          vm.$message.warning("请勾选需要删除的记录");
          return false;
        }
      }
      this.delVisible = true;
    },
    // 删除
    deleteRow() {
      if (this.Ids.length > 0) {
        this.delArrMessage(this);
      } else {
        this.delMessage(this);
      }
      this.delVisible = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.changePageCoreRecordData();
    },
    // 设置选中的方法
    setSelectRow() {
      const vm = this;
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
        return;
      }
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      this.$refs.mseeageItemTable.clearSelection();
      vm.$nextTick(() => {
        for (let i = 0; i < vm.messageList.length; i++) {
          if (selectAllIds.indexOf(vm.messageList[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="table"
            vm.$refs.mseeageItemTable.toggleRowSelection(
              vm.messageList[i],
              true
            );
          } else {
            vm.$refs.mseeageItemTable.toggleRowSelection(
              vm.messageList[i],
              false
            );
          }
        }
      });
    },
    // 记忆选择核心方法
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let that = this;
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.multipleSelectionAll.length <= 0) {
        this.multipleSelectionAll = this.multipleSelection;
        return;
      }
      // 总选择里面的key集合
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      let selectIds = [];
      // 获取当前页选中的id
      this.multipleSelection.forEach(row => {
        selectIds.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row);
        }
      });
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.messageList.forEach(row => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] === id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      });
    },
    handleStage() {
      this.$router.push({
        path: "/contract/stage/" + this.targetId
      });
    },
    readMsg(row) {
      this.msgId = row.msgId;
      this.readFrom.title = row.title;
      this.hasStage = row.msgContext.indexOf("#阶段名称") >= 0;
      this.targetId = row.targetId;
      this.readFrom.msgContext = row.msgContext
        .replace(/\[/g, "<span>[")
        .replace(/]/g, "]</span>")
        .split("#");
      this.readVisible = true;
      this.readMessage(this);
    },
    toContract(row) {
      if (row.msgType === "approve") {
        this.$router.push({
          path: "/task/task-detail",
          query: {
            taskId: row.targetId,
            businessId: row.targetId,
            type: row.targetType
          }
        });
      }
      if (row.msgType === "warning") {
        this.$router.push({
          path: "/contract/detail/" + row.targetId
        });
      }
    },
    handleSizeChange(val) {
      this.changePageCoreRecordData();
      this.current = 1;
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.changePageCoreRecordData();
      this.current = val;
      this.getData();
    }
  },
  filters: {
    msgFilter(param) {
      let res = "";
      switch (param) {
        case "system":
          res = "系统消息";
          break;
        case "approve":
          res = "审批消息";
          break;
        case "warning":
          res = "预警消息";
          break;
      }
      return res;
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
/deep/ .read-title {
  font-size: 16px;
  text-align: center;
  font-weight: bold;
  line-height: 1.5;
  letter-spacing: 2px;
}

/deep/ .read-content {
  width: 90%;
  max-height: 400px;
  margin: 20px auto;
  font-size: 14px;
  line-height: 1.5;
  letter-spacing: 1px;
  text-indent: 2em;
}

.result {
  text-align: center;
}

.result /deep/ span {
  color: #4977fc;
}
</style>
